<template>
  <div class="count">
    <div class="btn before"
      @click="down">-</div>
    <input type="text"
      :value="currentInputValue"
      @blur.prevent="handleInput" />
    <div class="btn after"
      @click="up">+</div>
  </div>
</template>

<script>
export default {
  props: {
    myNum: {
      type: Number,
      default: () => {
        return 1
      }
    },
    min: {
      type: Number
    },
    max: {
      type: Number
    }
  },
  data () {
    return {
      currentInputValue: this.myNum,
      currentMin: this.min,
      currentMax: this.max
    }
  },
  methods: {

    down: function () {
      if (this.currentMin != undefined) {
        if (parseInt(this.currentInputValue - 1) >= this.currentMin) {
          this.currentInputValue = this.currentInputValue - 1
          this.$emit('changeNum', parseInt(this.currentInputValue))
        }
      } else {
        this.currentInputValue = this.currentInputValue - 1
        this.$emit('changeNum', parseInt(this.currentInputValue))
      }
    },

    up: function () {
      if (this.currentMax != undefined) {
        if (parseInt(this.currentInputValue + 1) <= this.currentMax) {
          this.currentInputValue = this.currentInputValue + 1
          this.$emit('changeNum', parseInt(this.currentInputValue))
        }
      } else {
        this.currentInputValue = this.currentInputValue + 1
        this.$emit('changeNum', parseInt(this.currentInputValue))
      }
    },

    handleInput: function (e) {
      let value = e.target.value
      let emitValue = 1
      emitValue = parseInt(value)
      if (emitValue > this.currentMax) {
        emitValue = this.currentMax
      }
      if (emitValue < this.currentMin) {
        emitValue = parseInt(this.currentMin)
      }
      this.currentInputValue = emitValue
      this.$emit('changeNum', parseInt(this.currentInputValue))
    }
  }
}
</script>

<style lang="scss" scoped>
.count {
  display: flex;
  align-items: center;
  text-align: center;
  background-color: #eaeef1;
  height: 32px;
  line-height: 30px;
  user-select: none;
  border: 1px solid #bbb;
  border-radius: 2px;
  input {
    width: 60px;
    flex-shrink: 0;
    background-color: #fff;
    border-radius: 0;
    border: none;
    outline: none;
    padding: 0 15px;
    text-align: center;
    font-size: 12px;
    color: #666666;
  }
  .btn {
    width: 30px;
    flex-shrink: 0;
    font-size: 16px;
    cursor: pointer;
    color: #bbb;
  }
  .before {
    border-right: 1px solid #bbb;
  }
  .after {
    border-left: 1px solid #bbb;
  }
}
</style>
